package com.njtech.pet.controller;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.njtech.pet.constant.Constant;
import com.njtech.pet.entity.Friend;
import com.njtech.pet.entity.Power;
import com.njtech.pet.entity.User;
import com.njtech.pet.service.FriendService;
import com.njtech.pet.service.PowerService;
import com.njtech.pet.service.UserService;
import com.njtech.pet.utils.Md5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Author:gm
 * Date:2020-03-08 16:37
 * Description:<描述>用户的相关功能
 * 注意：所有保存结果用json
 * @author gmisa
 */

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    private FriendService friendService;
    @Autowired
    private PowerService powerService;

    /**
     * 功能1：检查待注册的用户名是否存在，用于ajax动态检查
     * @param username 用户名
     * @return         提示信息
     */
    @RequestMapping(value={"/registerUsernameCheck"},method = RequestMethod.POST)
    @ResponseBody
    public String registerUsernameCheck(@RequestParam("username") String username) {
        Map<String,Object> resultMap = new HashMap<>();
        if(username.equals("")||username==null){
            resultMap.put("result", "用户名不能为空！");
            return JSON.toJSONString(resultMap);
        }
        List<User> user= userService.selectByUserNameAndState(username,null);
        if(user.size()>0){
            resultMap.put("result", "notsuccess");
        }else {
            resultMap.put("result", "success");
        }
        return JSON.toJSONString(resultMap);
    }

    /**
     * @param username
     * @return true(可以注册)
     */
    public boolean checkUserName(String username){
        boolean flag=true;
        List<User> user= userService.selectByUserNameAndState(username,null);
        if(user.size()>0) {
            flag = false;
        }
        return flag;
    }

    /**
     *  * 功能2：注册
     * @param username 用户名
     * @param pwd  密码
     * @param pwdAgain  再一次密码
     * @param code  输入的验证码
     * @param originCode  原始验证码
     * @param sex  性别：男性/女性
     * @return
     * */
    @RequestMapping(value={"/regist"})
    @ResponseBody
    public String regist(@RequestParam String username,@RequestParam String pwd, @RequestParam String pwdAgain, @RequestParam String code, @RequestParam String originCode, @RequestParam String sex){
        User user=new User();
        Map<String,Object> resultMap = new HashMap<>();
        //非空判断
        if(username.equals("")||username==null||
                pwd.equals("")||pwd==null||
                pwdAgain.equals("")||pwdAgain==null||
                code.equals("")||code==null||
                originCode.equals("")||originCode==null||
                sex.equals("")||sex==null){
            resultMap.put("msg","不能有非空字段！");
            return JSON.toJSONString(resultMap);
        }
        boolean flag=checkUserName(username);
        //重名判断
        if(flag==false){
            resultMap.put("msg","用户名不能重复！");
            return JSON.toJSONString(resultMap);
        }else{
            //验证码判断
            if(!code.equals(originCode)){
                resultMap.put("msg","验证码有误！");
                return JSON.toJSONString(resultMap);
            }else{
                if(!pwd.equals(pwdAgain)){
                    resultMap.put("msg","两次密码不相同!");
                }else{
                    //插入一条数据
                    user.setUsername(username);
                    user.setPwd(Md5Util.MD5EncodeUtf8(pwd));
                    user.setHeadUrl("0.jpg");
                    user.setCredit(0);
                    user.setLevel(0);
                    user.setSex(sex);
                    user.setRole("普通用户");
                    user.setState(Constant.User.STATE_VALID.getValue());
                    String msg = userService.insert(user);
                    if(msg.equals("注册成功")) {
                        resultMap.put("msg", "注册成功！");
                    }
                }
            }
        }
        return JSON.toJSONString(resultMap);
    }

    /**
     * 功能3：用户和会员登录
     * @param username 用户名
     * @param pwd      密码
     * @param session
     * @return
     */
    @RequestMapping(value={"/login"},method = RequestMethod.POST)
    @ResponseBody
    public String login(@RequestParam String username,@RequestParam String pwd,HttpSession session){
        Map<String,Object> resultMap = new HashMap<>();
        //考虑空字符串情况
        if(username.equals("")||username==null||pwd.equals("")||pwd==null) {
            resultMap.put("msg","用户名或密码不能为空！");
            return JSON.toJSONString(resultMap);
        }
        User user = userService.findByName(username);
        //查找有效用户
        String pwdEncode= Md5Util.MD5EncodeUtf8(pwd);
        if (user==null||(user.getRole().length()>=3&&user.getRole().endsWith("管理员"))){
            //如果用户为空，或者用户为管理员则不能在此登录
            resultMap.put("msg","该用户不存在");
        }else{
            if (!pwdEncode.equals(user.getPwd())){
                //密码不正确
                resultMap.put("msg","用户名或密码不正确");
                return JSON.toJSONString(resultMap);
            }else {
                //session存储user对象
                session.setAttribute("user", user);
                session.setAttribute("uid", user.getId());
                System.out.println("用户的角色**********"+user.getRole());
                if(!user.getRole().equals(Constant.User.ROLE_SERVICE.getValue()))
                {
                    Friend friend = friendService.selectByUser(user, Constant.Friend.STATE_CUSTOMER_SERVICE.getValue(), null, null, null).get(0);
                    User servicer = friend.getFriend();
                    servicer = userService.selectByUserId(servicer.getId());
                    session.setAttribute("servicer", servicer);
                }
                resultMap.put("msg","欢迎登陆商城");
                resultMap.put("role",user.getRole());
                return JSON.toJSONString(resultMap);
            }
        }
        return JSON.toJSONString(resultMap);
    }

    /**
     * 功能4：管理员登录
     * @param username 用户名
     * @param pwd  密码
     * @param session
     * @return
     */
    @RequestMapping(value={"/loginManager"},method = RequestMethod.POST)
    @ResponseBody
    public String loginManager(@RequestParam String username,@RequestParam String pwd,HttpSession session){
        Map<String,Object> resultMap = new HashMap<>();
        //考虑空字符串情况
        if(username.equals("")||username==null||pwd.equals("")||pwd==null) {
            resultMap.put("msg","用户名或密码不能为空！");
            return JSON.toJSONString(resultMap);
        }
        User user = userService.findByName(username);
        //查找有效用户
        String pwdEncode= Md5Util.MD5EncodeUtf8(pwd);
        if (user==null||(user.getRole().equals("普通用户"))||(user.getRole().equals("会员"))){
            resultMap.put("msg","该用户不存在！");
        }else{
            if (!pwdEncode.equals(user.getPwd())){
                //密码不正确
                resultMap.put("msg","用户名或密码不正确");
                return JSON.toJSONString(resultMap);
            }else {
                //session存储user对象
                session.setAttribute("user", user);
                session.setAttribute("uid", user.getId());
                //session存储管理员的power
                List<Power> powerList = powerService.selectByUserAndPowerState(user,Constant.Power.STATE_VALID.getValue());
                List<String>powers = new ArrayList<>();
                for (Power temp : powerList) {
                    powers.add(temp.getPower());
                }
                session.setAttribute("powers",powers);
                System.out.println(powers);
                resultMap.put("msg","欢迎登陆管理后台！");
                return JSON.toJSONString(resultMap);
            }
        }
        return JSON.toJSONString(resultMap);

    }

    /**
     * 功能5：退出登录
     * @param session
     * @return
     */
    @RequestMapping(value={"/logout"},method = RequestMethod.POST)
    @ResponseBody
    public  String logout(HttpSession session) {
        session.removeAttribute("user");
        Map<String,Object> resultMap = new HashMap<>();
        resultMap.put("msg","已退出");
        return JSON.toJSONString(resultMap);
    }

    /**
     * 功能6：查询用户个人信息
     * @return json
     */
    @RequestMapping(value={"/userMessage"})
    @ResponseBody
    public String selectUser(@SessionAttribute(value = "user") User user){
        Gson gson = new Gson();
        String json;
        json = gson.toJson(user);
        return json;
    }


    /**
     * 功能7：更新用户个人信息
     * @param username    用户名
     * @param sex         性别
     * @param phone      手机号          00000
     * @return           提示信息
     */
    @RequestMapping(value={"/updateUser"})
    @ResponseBody
    public String  updateUser(@RequestParam String username, @RequestParam String sex, @RequestParam String phone, HttpSession session){
        Map<String,Object> resultMap = new HashMap<>();
        User user = (User)session.getAttribute("user");
        String uname = user.getUsername();
        if(username==null){
            resultMap.put("msg","用户名不能为空");
        }
        if(user!=null){
            List<User> user1= userService.selectByUserNameAndState(username,null);
            if((user1.size()==1&&uname.equals(username)) ||user1.size()==0) {
                //不重名,重新设置属性值
                user.setUsername(username);
                user.setSex(sex);
                user.setPhone(phone);
                int flag = userService.updateUser(user);
                if(flag==1){
                    session.removeAttribute("user");
                    session.setAttribute("user",user);
                    resultMap.put("msg","更新成功");
                }else{
                    resultMap.put("msg","更新失败");
                }
            }else{
                resultMap.put("msg","用户名已存在！");
            }
        }
        return JSON.toJSONString(resultMap);
    }

    /**
     * 功能8：修改密码
     * @param username
     * @param oldPwd  输入的旧密码
     * @param newPwd   输入的新密码
     * @return
     */
    @RequestMapping(value={"/changePwd"})
    @ResponseBody
    public String changePassword(@RequestParam String username ,@RequestParam String oldPwd,@RequestParam String newPwd,HttpSession session){
        Map<String,Object> resultMap = new HashMap<>();
        User user = userService.findByName(username);
        User operator =(User) session.getAttribute("user");
        String operatorRole = operator.getRole();
        String msg = userService.changePwd(operatorRole,user,newPwd,oldPwd);
        resultMap.put("msg",msg);
        return JSON.toJSONString(resultMap);
    }


    /**
     * 功能9：用户自行注销
     * @return   提示信息
     */
    @RequestMapping(value={"/logoff"})
    @ResponseBody
    public  String logoff(HttpSession session ) {
        Map<String,Object> resultMap = new HashMap<>();
        User user = (User)session.getAttribute("user");
        String username = user.getUsername();
        if(!username.equals("")&&username!=null){
            if(user!=null) {
                user.setState(Constant.User.STATE_INVALID.getValue());
                int flag = userService.updateUser(user);
                if(flag==1){
                    session.removeAttribute("user");
                    System.out.println(session.getAttribute("user"));
                    resultMap.put("msg","更新成功");
                }else{
                    resultMap.put("msg","更新失败");
                }
            }else{
                resultMap.put("msg","用户不存在！");
            }
        }else{
            resultMap.put("msg","用户名不能为空！");
        }
        return JSON.toJSONString(resultMap);
    }

    /**
     * 功能10：头像上传和更改
     * @param pic
     * @param uid
     * @throws IOException
     */
    @RequestMapping("/uploadPic")
    @ResponseBody
    public String  upload(MultipartFile pic, Integer uid, HttpServletRequest request) throws IOException {

        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        session.removeAttribute("user");
        Map<String,Object> resultMap = new HashMap<>();
        if(pic==null){
            resultMap.put("msg","没有上传文件");
            return JSON.toJSONString(resultMap);
        }
        String classpath = this.getClass().getResource("/").getPath().replaceFirst("/", "");
        String webappRoot = classpath.substring(0,classpath.length()-15);
        webappRoot=webappRoot+"src/main/webapp/avatar/";
        if (!pic.getOriginalFilename().equals("")){
            //获取文件的完整路径
            String originalFilename= pic.getOriginalFilename();
            String fileName=uid.toString();
            String ext=originalFilename.substring(originalFilename.lastIndexOf("."));
            if(ext.equals(".jpg")) {
                pic.transferTo(new File(webappRoot + fileName + ext));
                user.setHeadUrl(fileName + ext);
                session.setAttribute("user",user);
                int flag = userService.updateUser(user);
                if(flag==1){
                    resultMap.put("msg","上传成功");

                }else{
                    resultMap.put("msg","上传失败");
                }
            }else{
                resultMap.put("msg","仅允许扩展名为.jpg格式上传");
            }
        }else{
            resultMap.put("msg","没有上传文件");
        }
        return JSON.toJSONString(resultMap);
    }
}
